package com.example.advice.ExceptionHandler;

import com.example.common.core.AjaxResult;
import com.example.common.entity.ExcpErrResult;
import com.example.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author DestinyCc
 * @date 2022/4/18
 */
@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {
    /**
     * 统一异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Object commonExceptionHandler(HttpServletRequest request, Exception e){
//        log.warn(e.getMessage());
        e.printStackTrace();
        return ExcpErrResult.builder().code(-1).msg("操作失败").build();
    }

    @ExceptionHandler(ClassCastException.class)
    public Object castExceptionHandler(HttpServletRequest request, Exception e){
//        log.warn(e.getLocalizedMessage());
        return ExcpErrResult.builder().code(-2).msg("操作失败").data(e.getMessage()).build();
    }

    @ExceptionHandler(UndeclaredThrowableException.class)
    public Object undeclaredThrowableExceptionHandler(HttpServletRequest request, UndeclaredThrowableException e){
        return ExcpErrResult.builder().code(-3).msg("操作失败").data(e.getUndeclaredThrowable().getCause());
    }

    /**
     * 自定义异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Object baseExceptionHandler(HttpServletRequest request, BaseException e){
        log.warn(e.getLocalizedMessage());
        return ExcpErrResult.builder().code(e.getCode()).msg("操作失败").data(e.getMessage()).build();
    }
}
